package com.wyclabs.auth.common.config;


import com.wyclabs.auth.common.ClientRegisterUtil;
import com.wyclabs.auth.common.SecurityTokenGranter;
import com.wyclabs.auth.common.exception.SecurityExceptionTranslator;
import com.wyclabs.auth.common.properties.SecurityProperties;
import lombok.AllArgsConstructor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
import org.springframework.security.config.annotation.authentication.configuration.AuthenticationConfiguration;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerSecurityConfigurer;
import org.springframework.security.oauth2.provider.token.store.JwtAccessTokenConverter;


/**
 * SecurityAuthorizationServerConfig
 * @author rs
 * @date 2019/10/17
 */
@Configuration
@EnableAuthorizationServer
@Order(-2147483640)
@AllArgsConstructor
public class SecurityAuthorizationServerConfig extends AuthorizationServerConfigurerAdapter {

    private final SecurityProperties securityProperties;

    private final PasswordEncoder passwordEncoder;

    private final UserDetailsService userDetailsService;

    private final TokenStoreConfig tokenStoreConfig;

    private final AuthenticationConfiguration authenticationConfiguration;

    private final JwtAccessTokenConverter jwtAccessTokenConverter;

    @Bean
    public SecurityExceptionTranslator securityExceptionTranslator() {
        return new SecurityExceptionTranslator();
    }

    /**
     * 用来配置客户端详情服务（ClientDetailsService），客户端详情信息在这里进行初始化，你能够把客户端详情信息写死在这里或者是通过数据库来存储调取详情信息。
     */
    @Override
    public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
        ClientRegisterUtil.register(clients, securityProperties, passwordEncoder);
    }

    /**
     * 用来配置授权（authorization）以及令牌（token）的访问端点和令牌服务(token services)。
     */
    @Override
    public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
        endpoints.tokenStore(tokenStoreConfig.redisTokenStore())
                .accessTokenConverter(jwtAccessTokenConverter)
                .userDetailsService(userDetailsService)
                .exceptionTranslator(securityExceptionTranslator())
                .reuseRefreshTokens(false)
                .tokenGranter(SecurityTokenGranter.getInstance(endpoints)
                        .authenticationManager(authenticationConfiguration.getAuthenticationManager())
                );
    }

    /**
     * 用来配置令牌端点(Token Endpoint)的安全约束.
     */
    @Override
    public void configure(AuthorizationServerSecurityConfigurer security) throws Exception {
        security.allowFormAuthenticationForClients()
                .tokenKeyAccess("isAuthenticated()")
                .checkTokenAccess("permitAll()");
    }
}
